package day12;

import java.util.Random;

/**
 * @author oldliu
 * @since 1.0
 */
//取钱人
public class Taker2 extends Thread {
    private final Accout ac;

    public Taker2(String name, Accout ac) {
        super(name);
        this.ac = ac;
    }

    @Override
    public void run() {
        Random rd = new Random();


        while (true) {
            int rmb = rd.nextInt(500);
            System.out.println(this.getName() + "打算取钱：" + rmb + "元，当前余额是" + ac.getMoney() + "元");
            synchronized (ac) {
                try {
                    while (ac.getMoney() < rmb) {
                        System.out.println(this.getName() + "等着！！！");
                        ac.wait();//停了，锁释放
                        System.out.println(this.getName() + "被喊醒，余额是："+ac.getMoney()+"元");
                    }
                    sleep((long) (100 * Math.random()));

                    boolean ok = ac.withDraw(rmb);
                    System.out.println(this.getName() + "取钱" + rmb + "元" + "，当前余额是" + ac.getMoney() + "元");


                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
